import { ref } from "vue";

export function useChat() {
  const userInput = ref("");
  const conversationHistory = ref([]);

  const handleSend = async () => {
    const message = userInput.value.trim();
    if (!message) return;

    conversationHistory.value.push({
      role: "user",
      content: message,
    });

    const assistantMessageIndex = conversationHistory.value.length;
    conversationHistory.value.push({
      role: "assistant",
      reasoning: "",
      content: "",
    });

    userInput.value = "";

    try {
      const response = await fetch("http://localhost:8080/api/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          contents: message,
          history: conversationHistory.value.map((msg) => ({
            role: msg.role,
            content: msg.content || "",
            ...(msg.role === "assistant" && msg.reasoning
              ? { reasoning: msg.reasoning }
              : {}),
          })),
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split("\n").filter((line) => line.trim());

        for (const line of lines) {
          try {
            const responses = JSON.parse(line);
            if (Array.isArray(responses)) {
              responses.forEach((response) => {
                if (response.reasoningContent != null) {
                  conversationHistory.value[assistantMessageIndex].reasoning +=
                    response.reasoningContent;
                }
                if (response.content != null) {
                  conversationHistory.value[assistantMessageIndex].content +=
                    response.content;
                }
              });
            } else if (typeof responses === "object") {
              if (responses.reasoningContent != null) {
                conversationHistory.value[assistantMessageIndex].reasoning +=
                  responses.reasoningContent;
              }
              if (responses.content != null) {
                conversationHistory.value[assistantMessageIndex].content +=
                  responses.content;
              }
            }
          } catch (e) {
            console.debug("解析JSON时出错:", e, "原始数据:", line);
          }
        }
      }
    } catch (error) {
      console.error("Error:", error);
      conversationHistory.value[assistantMessageIndex] = {
        role: "assistant",
        reasoning: "",
        content: "抱歉,发生错误,请稍后重试。错误信息：" + error.message,
      };
    }
  };

  return {
    userInput,
    conversationHistory,
    handleSend,
  };
}
